package br.com.sgi.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletResponse;

public final class FacesUtils implements Serializable {

	private static final long serialVersionUID = -3859582133507483309L;

	private static final String FACES_REDIRECT_TRUE = "faces-redirect=true";
	public static final String PARAMETRO_JSF_REDIRECT = "?" + FACES_REDIRECT_TRUE;
	private final static Pattern REDIRECT_EX = Pattern.compile("(.*?)[?&]" + FACES_REDIRECT_TRUE + "$");

	protected static String getDefaultViewSuffix(FacesContext facesContext) {
		final String suffix = facesContext.getExternalContext().getInitParameter("javax.faces.DEFAULT_SUFFIX");
		return suffix != null ? suffix : ".jsp";
	}

	protected static String getTargetViewId(FacesContext facesContext, String outcome) {
		String targetViewId;
		String viewSuffix = getDefaultViewSuffix(facesContext);

		if (isRedirect(outcome)) {
			Matcher m = REDIRECT_EX.matcher(outcome);
			m.matches();
			targetViewId = m.group(1) + viewSuffix;
		} else {
			targetViewId = outcome + viewSuffix;
		}
		if (!targetViewId.startsWith("/")) {
			String currentViewId = facesContext.getViewRoot().getViewId();
			int index = currentViewId.lastIndexOf('/');
			if (index == -1) {
				index = 0;
			}
			targetViewId = currentViewId.substring(0, index) + "/" + targetViewId;
		}
		return targetViewId;
	}

	protected static boolean isRedirect(String outcome) {
		return REDIRECT_EX.matcher(outcome).matches();
	}

	
	protected static boolean wildCardMatch(String text, String pattern) {
		if (pattern.equals("*")) {
			return true;
		}

		// Create the cards by splitting using a RegEx. If more speed
		// is desired, a simpler character based splitting can be done.
		String[] cards = pattern.split("\\*");

		// Iterate over the cards.
		for (String card : cards) {
			int idx = text.indexOf(card);

			// Card not detected in the text.
			if (idx == -1) {
				return false;
			}

			// Move ahead, towards the right of the text.
			text = text.substring(idx + card.length());
		}

		return true;
	}
	
	public static void disponibilizarParaDownload(File arquivo, String nomeArquivo) {
      disponibilizarParaDownload(arquivo, FacesContext.getCurrentInstance(), nomeArquivo);
   }
	
   /**
    * Disponibilizar para download.
    *
    * @param arquivo the arquivo
    * @param facesContext the faces context
    */
   public static void disponibilizarParaDownload(File arquivo, FacesContext facesContext, String nomeArquivo) {
      try {
         HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
         response.setContentType("application/octet-stream");
         response.setHeader("Cache-Control", "no-cache");
         response.setHeader("Content-Disposition", "attachment;filename="+nomeArquivo.toString().trim()  );
         response.setCharacterEncoding("UTF-8");

         OutputStream stream = response.getOutputStream();
         FileInputStream in = new FileInputStream(arquivo);

         byte[] buf = new byte[(int) arquivo.length()];
         int count;
         while ((count = in.read(buf)) >= 0) {
            stream.write(buf, 0, count);
         }
         in.close();

         stream.flush();
         stream.close();

         facesContext.responseComplete();
      } catch (Exception e) {
         e.getMessage();
      }
   }

}